package net.awpspace.mobile.management.book;

import java.util.Vector;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.Image;
import javax.microedition.midlet.MIDlet;

import net.awpspace.mobile.Application;
import net.awpspace.mobile.form.BaseForm;
import net.awpspace.mobile.global.Client;
import net.awpspace.mobile.global.Utils;

import com.nokia.mid.ui.CategoryBar;
import com.nokia.mid.ui.ElementListener;
import com.nokia.mid.ui.IconCommand;
import com.sun.lwuit.events.ActionEvent;

/**
 * Book management
 * 
 * @author Diep
 * 
 */
public class BookManagement extends BaseForm implements ElementListener {

	private static final int UI_LIST = 0;
	private static final int UI_DELETE = 1;
	private static final int UI_INSERT = 2;

	private Vector books;

	public BookManagement(MIDlet app, BaseForm parent) {
		super(app, parent);
		createCategoryBar();
		new Thread() {

			public void run() {
				books = Client.getInstance().loadBooks();
				onDataLoaded();
			}
		}.start();
	}

	public void notifyElementSelected(CategoryBar categoryBar, int selectedIndex) {
		switch (selectedIndex) {
		case ElementListener.BACK:
			categoryBar.setVisibility(false);
			showBack();
			break;
		default:
			books = Client.getInstance().loadBooks();
			createComponents(selectedIndex);
			break;
		}
	}

	protected void processCommand(ActionEvent e) {
	}

	private void createComponents(int mode) {
		switch (mode) {
		case UI_LIST:
			new ViewList(app, parent, books).show();
			break;
		case UI_DELETE:
			new ViewDelete(app, parent, books).show();
			break;
		case UI_INSERT:
			new ViewInsert(app, parent, null).show();
			break;
		default:
			return;
		}
	}

	private void createCategoryBar() {
		Vector commands = new Vector();

		Image imgList = Utils.load(Utils.ICON_BOOK_LIST);
		Image imgDelete = Utils.load(Utils.ICON_BOOK_DELETE);
		Image imgInsert = Utils.load(Utils.ICON_BOOK_INSERT);

		commands.addElement(new IconCommand("list", imgList, null,
				Command.SCREEN, 1));
		commands.addElement(new IconCommand("delete", imgDelete, null,
				Command.SCREEN, 1));
		commands.addElement(new IconCommand("insert", imgInsert, null,
				Command.SCREEN, 1));

		IconCommand[] iconCommands = new IconCommand[3];

		for (int i = 0; i < 3; i++) {
			iconCommands[i] = (IconCommand) commands.elementAt(i);
		}

		CategoryBar categoryBar = new CategoryBar(iconCommands, true);
		categoryBar.setElementListener(this);
		((Application) app).setCategoryBar(categoryBar, true);
	}

	/**
	 * Notify data loaded
	 */
	private void onDataLoaded() {
		if (books == null) {
			books = new Vector();
		}
		createComponents(UI_LIST);
	}
}
